﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using System.Data.SqlClient;
using System.Threading;

namespace IReader_demo
{
    public partial class Form1 : Form
    {
        ik.DB.clDB ClDb = null;
        DataTable dt = new DataTable();

        System.Diagnostics.Stopwatch stopWatch = new System.Diagnostics.Stopwatch();
        Boolean Alivio = true;

        public Form1()
        {
            InitializeComponent();
            cnnType.OnConnect += new ConnectionBuilder.DatabaseType.ConnectDelegate(cnnType_OnConnect);
            cnnType.OnError += new ConnectionBuilder.DatabaseType.ErrorDelegate(cnnType_OnError);
        }

        void cnnType_OnError(Exception e)
        {
            MessageBox.Show(e.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        void cnnType_OnConnect(ik.DB.enSGBD sgbd)
        {
            ClDb = cnnType.clDb;
            button1_Click(null, new EventArgs());
        }


        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                stopWatch.Start();

                //executa uma thread
                CheckForIllegalCrossThreadCalls = false;
                new Thread(new ThreadStart(Execute)).Start();

                // aguarda a thread terminar
                System.Diagnostics.Stopwatch stopWatchDoEvents = new System.Diagnostics.Stopwatch();
                stopWatchDoEvents.Start();
                while (Alivio)
                {
                    if (stopWatchDoEvents.Elapsed.Seconds >= 1)
                    {
                        ShowTime();
                        Application.DoEvents();

                        stopWatchDoEvents.Reset();
                        stopWatchDoEvents.Start();
                    }
                    Thread.Sleep(10);
                }
                stopWatchDoEvents.Stop();

                ShowTime();
                stopWatch.Reset();
                stopWatch.Start();

                dataGridView1.DataSource = dt;

                stopWatch.Stop();
                this.Text += " - Load Grid: " + stopWatch.Elapsed.ToString();

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void ShowTime()
        {
            this.Text = "Load SQLReader: " + stopWatch.Elapsed.ToString();
        }

        //thread simples
        private void Execute()
        {
            try
            {
                String SQLquery = "select name from sys.sysdatabases order by 1";
                IDataReader _dr = ClDb.GetDataReader(SQLquery);

                //dt.Load(_dr);
                dt = ik.Data.Utils.DataReaderConverters.ConvertDataReaderToDataTable(_dr);
                _dr.Close();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                GC.Collect();
                Alivio = false;
            }
        }

    }
}



namespace ik.Data.Utils
{
    public class DataReaderConverters
    {
        /// <summary>
        /// [static] ik.Data.Utils.DataReaderConverters.ConvertDataReaderToDataSet:
        /// Converts one or more resultsets returned in a SqlDataReader to a DataSet
        /// </summary>
        /// <param name="reader">IDataReader</param>
        /// <returns>System.Data.DataSet</returns>
        public static DataSet ConvertDataReaderToDataSet(IDataReader reader)
        {
            DataSet dataSet = new DataSet();
            do
            {
                // Create new data table
                DataTable schemaTable = reader.GetSchemaTable();
                DataTable dataTable = new DataTable();

                if (schemaTable != null)
                {
                    for (int i = 0; i < schemaTable.Rows.Count; i++)
                    {
                        DataRow dataRow = schemaTable.Rows[i];
                        // Create a column name that is unique in the data table
                        String columnName = (String)dataRow["ColumnName"];
                        // Add the column definition to the data table
                        DataColumn column = new DataColumn(columnName, (Type)dataRow["DataType"]);
                        dataTable.Columns.Add(column);
                    }

                    dataSet.Tables.Add(dataTable);

                    while (reader.Read())
                    {
                        DataRow dataRow = dataTable.NewRow();

                        for (int i = 0; i < reader.FieldCount; i++)
                            dataRow[i] = reader.GetValue(i);

                        dataTable.Rows.Add(dataRow);
                    }
                }
                else
                {
                    // No records returned

                    DataColumn column = new DataColumn("RowsAffected");
                    dataTable.Columns.Add(column);
                    dataSet.Tables.Add(dataTable);
                    DataRow dataRow = dataTable.NewRow();
                    dataRow[0] = reader.RecordsAffected;
                    dataTable.Rows.Add(dataRow);
                }
            }
            while (reader.NextResult());
            return dataSet;
        }

        /// <summary>
        /// [static] ik.Data.Utils.DataReaderConverters.ConvertDataReaderToDataTable
        /// converts SqlDataReader to a DataTable
        /// </summary>
        /// <param name="reader">IDataReader</param>
        /// <returns>System.Data.DataTable</returns>
        public static DataTable ConvertDataReaderToDataTable(IDataReader reader)
        {
            System.Data.DataTable table = reader.GetSchemaTable();
            System.Data.DataTable dt = new System.Data.DataTable();
            System.Data.DataColumn dc;
            System.Data.DataRow row;
            System.Collections.ArrayList al = new System.Collections.ArrayList();

            for (int i = 0; i < table.Rows.Count; i++)
            {
                dc = new System.Data.DataColumn();
                if (!dt.Columns.Contains(table.Rows[i]["ColumnName"].ToString()))
                {
                    dc.ColumnName = table.Rows[i]["ColumnName"].ToString();
                    dc.Unique = Convert.ToBoolean(table.Rows[i]["IsUnique"]);
                    dc.AllowDBNull = Convert.ToBoolean(table.Rows[i]["AllowDBNull"]);
                    dc.ReadOnly = Convert.ToBoolean(table.Rows[i]["IsReadOnly"]);
                    al.Add(dc.ColumnName);
                    dt.Columns.Add(dc);
                }
            }
            while (reader.Read())
            {
                row = dt.NewRow();
                for (int i = 0; i < al.Count; i++)
                {
                    row[((System.String)al[i])] = reader[(System.String)al[i]];
                }
                dt.Rows.Add(row);
            }
            return dt;
        }
    } // end class
} // end namespace
